package IO;

import java.io.*;
import java.nio.file.Files;
import java.util.Scanner;

import static java.awt.geom.Path2D.contains;

//输入一个目录，查询该目录所有的文件看是否有关键字
public class Demo13 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个源路径");
        String srcrootdirpath = scanner.next();
        System.out.println("请输入查询的关键字");
        String word = scanner.next();
        File rootDir = new File(srcrootdirpath);  //判断源路径是否有误
        if(!rootDir.isDirectory()) {
            System.out.println("输入源路径有误");
            return;
        }
        scandir(rootDir,word);
    }
    public static void scandir(File rootDir,String word) throws IOException {
        File[] files = rootDir.listFiles();
        if(files == null) {
            return;
        }
        for (File f:files) {
            if(f.isFile()) {
                if(containsWord(f,word)) {
                    System.out.println(f.getCanonicalFile());
                }
            }else if(f.isDirectory()) {
                scandir(f,word);
            }
        }
    }

    private static boolean containsWord(File f, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)) {
            char[] buffer = new char[1024];
            while (true) {
                int len = reader.read(buffer);
                if(len == -1) {
                    break;
                }
                stringBuilder.append(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.indexOf(word) != -1;
    }
}
